package lormi.meipin.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import lormi.meipin.common.Result;
import lormi.meipin.util.PropertiesUtils;

public class LMExceptionInterceptor extends SimpleMappingExceptionResolver  {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception ex) {
		//输出异常便于调试
		ex.printStackTrace();
		
		//创建ModelAndView对象用于返回
		ModelAndView mv = new ModelAndView();
		//设置返回内容
		Result re = new Result();
		re.setResult(0);
		re.setCode(ex.getMessage());
		if(ex.getMessage()==null || ex.getMessage().length()!=6){
			re.setCode("100002");
		}
		re.setMessage(PropertiesUtils.getMsg(re.getCode()));
		//设置状态码
		response.setStatus(HttpStatus.OK.value());
		//设置ContentType
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		//避免乱码
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control","no-cache, must-revalidate");
		try {
			//输出json异常
			response.getWriter().write(re.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mv;
	}
}
